#!/usr/bin/env python
# -*- coding: utf-8 -*-
#code:utf-8
#
# Copyright(C) 2011 SupDo.com
# Licensed under the GUN License, Version 3.0 (the "License");
# 
# File:          articleView.py
# Author:      KuKei
# Create Date: 2012-03-19
# Description: 图片管理视图
# Modify Date: 2012-03-19

from sd.cms.views import BaseView
from sd.cms.lib.decorator import powerLevel
from sd.cms.lib import Params, Pager, SDFileSystemStorage, Result
from django.http import HttpResponse
from django.utils import simplejson
from sd.cms.lib.utility import *
from sd.cms.models.appModel import Image
from sd.cms.forms.appForm import ImageForm
import datetime, random, os, hashlib

class ImageView(BaseView):
    def __init__(self, request, dir):
        BaseView.__init__(self, request)
        self.fs = SDFileSystemStorage(dir)
        
    @powerLevel(Params.ADMINISTRATOR)
    def upload(self, **args):
        if self.request.method=='POST':
            content = self.request.FILES['image']
            namelist = getFileName(content.name.encode('utf-8'))
            dateStr = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
            if not self.checkImg(content):
                return self.render('/snippet/ajaxIFrame.html')
            filename = args['path'][1:]+'/'+dateStr+str(random.randint(100, 100000))+'_'+hashlib.sha1(namelist[0]).hexdigest()+namelist[1]
            self.fs.save(filename, content)
            self.result.flag = True;
            self.result.msg = '上传成功！';
            self.result.toUrl = filename;
        return self.render('/snippet/ajaxIFrame.html')
    
    @powerLevel(Params.ADMINISTRATOR)
    def mkdir(self, **args):
        if self.request.method=='POST':
            dir = self.request.POST['dir'] if self.request.POST.has_key('dir') else u''
            dir = dir.encode('utf-8')
            if not isEng(dir):
                return self.render_json(Result(False, '目录名只能是字母、数字或下划线', '', '', 3))
            if dir.find('/') > -1:
                return self.render_json(Result(False, '只能创建一级目录', '', '', 3))
            if self.fs.exists(dir):
                return self.render_json(Result(False, '"'+dir+'"此目录已存在', '', '', 3))
            os.makedirs(self.fs.path(dir))
            return self.render_json(Result(True, '目录创建成功！', '', '', 3))
        else:
            return self.render_json(Result(False, '不支持此种方式', '', '', 3))
        
    @powerLevel(Params.ADMINISTRATOR)
    def ueditor(self, **args):
        retFlag = 'SUCCESS'
        if self.request.method=='POST':
            year, month = str(datetime.date.today())[0:4], str(datetime.date.today())[5:7]
            try:
                content = self.request.FILES['picdata']
                if not self.checkImg(content):
                    retFlag = 'FAILURE'
                    return HttpResponse(simplejson.dumps({'info':self.result.msg,'url':'','title':'图片','state':retFlag}))
                namelist = getFileName(content.name.encode('utf-8'))
                dateStr = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
                filename = '%s/%s/%s'%(year,int(month),dateStr+str(random.randint(100, 100000))+'_'+hashlib.sha1(namelist[0]).hexdigest()+namelist[1])
                self.fs.save(filename, content)
            except Exception,ex:
                retFlag = 'FAILURE'
        self.rtor = HttpResponse(simplejson.dumps({'info':'上传成功！','url':filename,'title':'图片','state':retFlag}))
        return self.rtor
    
    @powerLevel(Params.ADMINISTRATOR)
    def delete(self, **args):
        if self.request.method=='POST':
            path = self.request.POST['path'] if self.request.POST.has_key('path') else args['path']
            name = self.request.POST['name']
            self.fs.delete(path[1:]+'/'+name)
            self.result = Result(True,'成功！','','',3)
            return self.render_json()
        else:
            return self.render_json(Result(False, '不支持此种方式', '', '', 3))
    
    @powerLevel(Params.ADMINISTRATOR)
    def rmdir(self, **args):
        if self.request.method=='POST':
            dir = self.request.POST['path'] if self.request.POST.has_key('path') else ''
            name = self.request.POST['name'] if self.request.POST.has_key('name') else ''
            fname = dir+name
            if name.find('/') > -1:
                return self.render_json(Result(False, '只能删除一级目录', '', '', 3))
            if not self.fs.exists(fname):
                return self.render_json(Result(False, '此目录不存在', '', '', 3))
            if not self.fs.listdir(fname) == ([],[]):
                return self.render_json(Result(False, '此目录存在文件不允许删除', '', '', 3))
            os.rmdir(self.fs.path(fname))
            return self.render_json(Result(True, '目录删除成功！', '', '', 3))
        else:
            return self.render_json(Result(False, '不支持此种方式', '', '', 3))
        
    def listView(self, **args):
        retlist = []
        pager = Pager(self.request, 'img')
        dirlist, imglist = self.fs.listdir(nvl(args['path'],'0')[1:])
        for e in dirlist:
            retlist.append({'type':'dir', 'name':e})
        for e in imglist:
            retlist.append({'type':'img', 'name':e})
        pager.totalSize = len(retlist)
        self.viewData['imglist'] = retlist[pager.startSize:pager.getEndSize()]
        self.viewData['pager'] = pager.getPageList()
        self.viewData['path'] = {'dir':nvl(args['dir'],''),'path':nvl(args['path'],'')}
        return self.render('/listImage.html')
    
    @powerLevel(Params.ADMINISTRATOR)
    def imgsView(self, **args):
        pager = Pager(self.request, 'img')
        dirlist = self.fs.listdir('')[0]
        for e in dirlist:
            if e.find('.') > -1:
                dirlist.remove(e)
        dir = args['path'][1:] if args.has_key('path') and args['path'] else dirlist[0] if len(dirlist) > 0 else None
        imglist = self.fs.listdir(dir)[1] if dir else []
        pager.totalSize = len(imglist)
        self.viewData['dirlist'] = dirlist
        self.viewData['imglist'] = imglist[pager.startSize:pager.getEndSize()]
        self.viewData['pager'] = pager.getPageList()
        self.viewData['path'] = {'dir':nvl(args['dir'],''),'path':dir}
        return self.render('/listimgs.html')
    
    def uploadView(self, **args):
        self.viewData['path'] = {'dir':nvl(args['dir'],''),'path':args['path'][1:] if args['path'] else ''}
        return self.render('/uploadimg.html')
    
    def dirlistview(self, **args):
        dirlist = self.fs.listdir('')[0]
        self.viewData['dirlist'] = dirlist
        
    def checkImg(self, img):
        if img.size > 200*1024:
            self.result = Result(False, '上传的文件太大了!', '', '' ,3)
            return self.result.flag
        if img.content_type.split('/')[0] not in ('image') and img.name.split('.')[-1] not in ('jpg','jpeg','gif','png'):
            self.result = Result(False, '只能上传图片!', '', '' ,3)
            return self.result.flag
        return True
    
    def picsListView(self, **args):
        imagesForm = ImageForm()
        imagesList = None
        kind = args['kind'] if args.has_key('kind') else 1
        imagesModels = list(Image.objects.filter(kind = kind).order_by('orderby'))
        imagesList = []
        for i in imagesModels:
            myParamForm = ImageForm(self,modelData=i)
            imagesList.append(myParamForm)
        self.viewData['imagesList'] = imagesList
        self.viewData['imagesForm'] = imagesForm
        return self.render('/admin/picsList.html')
    
    def picsDetailView(self, **args):
        image = Image.objects.get(id=int(args['id']))
        imageForm = ImageForm(self,modelData=image)
        self.viewData["etype"] = 'image'
        self.viewData["e"] = imageForm
        return self.render('/admin/include/detail.html')
    
    def picsAdd(self, **args):
        try:
            imagesForm = ImageForm()
            if self.request.POST:
                imagesForm = ImageForm(self)
                if imagesForm.is_valid():
                    formData = imagesForm.cleaned_data
                    imagesModel = Image().initData(formData)
                    imagesModel.save()
                    self.result = Result(True,'操作成功！','','',2)
                    self.mc.flushNS2(self.params.IMAGELIST)
                else:
                    self.result = Result(False,imagesForm.GetErrors(),'','',3)
        except Exception, ex:
            self.result = Result(False,ex.message,'','/admin/list!Param/'+args['kind']+'.html',3)
        finally:
            return self.render_json()
        
    def picsEdit(self, **args):
        imagesForm = ImageForm()
        if self.request.POST:
            imagesForm = ImageForm(self)
            if imagesForm.is_valid():
                formData = imagesForm.cleaned_data
                objId = int(self.request.POST['_id'])
                if objId > -1:
                    imagesModel = Image().initData(formData)
                    imagesModel.id = objId
                    imagesModel.save()
                    self.result = Result(True,'操作成功！','','',2)
                    self.mc.flushNS2(self.params.IMAGELIST)
                else:
                    self.result = Result(False,imagesForm.GetErrors(),'','',3)
            else:
                self.result = Result(False,imagesForm.GetErrors(),'','',3)
        return self.render_json()
        
    def picsDelete(self, **args):
        if self.request.POST:
            paramModel = Image.objects.get(id=int(args['id']))
            paramModel.delete()
            self.result.flag = True
            self.result.msg = "删除成功！"
            self.mc.flushNS2(self.params.IMAGELIST)
        return self.render_json()
    
def action(request, **args):
    return apply(ImageView(request, args['dir'] if args.has_key('dir') else 'images').action, (), args)
